﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace LegendStats
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        string path_statdir = "C:\\Riot Games\\League of Legends\\RADS\\projects\\lol_air_client\\releases\\0.0.0.69\\deploy\\history\\json";
        private void Form1_Load(object sender, EventArgs e)
        {
            if (!Directory.Exists(path_statdir))
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.ShowNewFolderButton = false;
                fbd.Description = "Please set the stats folder.  This should have been: \r\n C:\\Riot_Games\\League_of_Legends\\RADS\\projects\\lol_air_client\\releases\\0.0.0.69\\deploy\\history\\json";
                if (fbd.ShowDialog() == DialogResult.OK)
                {
                    path_statdir = fbd.SelectedPath;
                }
            }
            if (!Directory.Exists(path_statdir))
            {
                MessageBox.Show(this, "Can't find stats folder.  LegendStats will now quit.");
                this.Close();
            }
            DirectoryInfo di = new DirectoryInfo(path_statdir);
            foreach (FileInfo fi in di.GetFiles("*.jeog"))
            {
                cbbGameChoice.Items.Add(fi.Name);
            }
        }
        private void cbbGameChoice_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selection = (string)cbbGameChoice.SelectedItem;
            string path_gamefile = Path.Combine(path_statdir, selection);
            displayGame(path_gamefile);
        }
        private void displayGame(string path_gamefile)
        {
            StreamReader sr = new StreamReader(path_gamefile);
            string json = sr.ReadToEnd();
            sr.Close();
            int pos1 = json.IndexOf('{');
            json = json.Substring(pos1);
            JObject o = JObject.Parse(json);
            #region participants
            JToken team1 = o["endOfGameStats"]["teamPlayerParticipantStats"];
            JToken team2 = o["endOfGameStats"]["otherTeamPlayerParticipantStats"];
            bool lvPrepped = false;
            string[] statKeys = null;
            lvPlayers.Items.Clear();
            lvPlayers.Columns.Clear();
            foreach (JObject player in team1["source"].Union(team2["source"]))
            {
                if (!lvPrepped)
                {
                    string[] presetKeys = getPresetKeys();
                    statKeys = getPlayerStatSourceKeys(player);
                    foreach (string col in presetKeys)
                        lvPlayers.Columns.Add(col);
                    foreach (string col in statKeys)
                        lvPlayers.Columns.Add(col);
                    lvPrepped = true;
                }
                ArrayList al = new ArrayList();
                al.Add((string)player["summonerName"]);
                al.Add(((int)player["wins"]).ToString());
                al.Add(((int)player["losses"]).ToString());
                al.Add(((int)player["leaves"]).ToString());
                al.Add(((bool)player["leaver"]).ToString());
                al.Add((string)player["skinName"]);//champion
                al.Add(((int)player["teamId"]).ToString());
                al.Add(((bool)player["botPlayer"]).ToString());
                foreach (string col in statKeys)
                {
                    bool colFound = false;
                    foreach (JObject stat in player["statistics"]["list"]["source"])
                    {
                        if ((string)stat["displayName"] == col)
                        {

                            string val_str = "";
                            switch (stat["value"].Type)
                            {
                                case JTokenType.Integer:
                                    val_str = ((int)stat["value"]).ToString();
                                    break;
                                default:
                                    val_str = (string)stat["value"];
                                    break;
                            }
                            al.Add(val_str);
                            colFound = true;
                        }
                    }
                    if (!colFound) al.Add("");
                }
                ListViewItem lvi = new ListViewItem((string[])al.ToArray(typeof(string)));
                lvPlayers.Items.Add(lvi);
            }
            #endregion
            #region Game Properties
            tbGame.Text = "";
            try { tbGame.Text += "Length:               " + ((int)o["endOfGameStats"]["gameLength"] / 60).ToString() + " minutes" + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Base Points:          " + ((int)o["endOfGameStats"]["basePoints"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "IP Earned:            " + ((int)o["endOfGameStats"]["ipEarned"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Boost IP Earned:      " + ((int)o["endOfGameStats"]["boostIpEarned"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Queue Bonus Earned:   " + ((int)o["endOfGameStats"]["queueBonusEarned"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "IP Total:             " + ((int)o["endOfGameStats"]["ipTotal"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "XP Earned:            " + ((int)o["endOfGameStats"]["experienceEarned"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Tutorial Type:        " + o["gameModel"]["tutorialType"] + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Ranked:               " + ((bool)o["gameModel"]["ranked"]).ToString() + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Type:                 " + o["gameModel"]["gameType"] + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Type2:                " + o["endOfGameStats"]["gameType"] + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Difficulty:           " + o["gameModel"]["difficulty"] + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Mode:                 " + o["gameModel"]["gameMode"] + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Map:                  " + o["gameModel"]["gameMap"]["displayName"] + Environment.NewLine; }
            catch { }
            try { tbGame.Text += "Players:              " + o["gameModel"]["gameMap"]["totalPlayers"] + Environment.NewLine; }
            catch { }
            #endregion
        }
        private string[] getPresetKeys()
        {
            ArrayList al = new ArrayList();
            al.Add("Summoner");
            al.Add("Career Wins");
            al.Add("Career Losses");
            al.Add("Career Leaves");
            al.Add("Left Game");
            al.Add("Champion");
            al.Add("Team ID");
            al.Add("Bot");
            return (string[])al.ToArray(typeof(string));
        }
        private string[] getPlayerStatSourceKeys(JObject player)
        {
            ArrayList al = new ArrayList();
            al.Add("Champions Killed");
            al.Add("Deaths");
            al.Add("Assists");
            foreach (JObject stat in player["statistics"]["list"]["source"])
            {
                string header = (string)stat["displayName"];
                if (!al.Contains(header))
                    al.Add(header);
            }
            al.Sort(3, al.Count - 3, new statSourceComparer());

            return (string[])al.ToArray(typeof(string));
        }
        class statSourceComparer : IComparer
        {
            int IComparer.Compare(object a, object b)
            {
                var b1 = (string)a;
                var b2 = (string)b;
                return string.Compare(b1, b2);
            }
        }
        private Hashtable getAllData(string path_database)
        {
            ArrayList allJson = new ArrayList();
            foreach (FileInfo fi in new DirectoryInfo(path_database).GetFiles("*.jeog"))
            {
                StreamReader sr = new StreamReader(fi.FullName);
                string json = sr.ReadToEnd();
                sr.Close();
                int pos1 = json.IndexOf('{');
                json = json.Substring(pos1);
                JObject o = JObject.Parse(json);
                allJson.Add(o);
                Hashtable allChamps = new Hashtable();
                JToken team1 = o["endOfGameStats"]["teamPlayerParticipantStats"];
                JToken team2 = o["endOfGameStats"]["otherTeamPlayerParticipantStats"];
                foreach (JObject player in team1["source"].Union(team2["source"]))
                {
                    string summonerName = (string)player["summonerName"];
                    allChamps["summonerName"] = summonerName;
                    allChamps["wins"] = ((int)player["wins"]).ToString();
                    allChamps["losses"] = ((int)player["losses"]).ToString();
                    allChamps["leaves"] = ((int)player["leaves"]).ToString();
                    allChamps["leaver"] = ((bool)player["leaver"]).ToString();
                    allChamps["skinName"] =(string)player["skinName"];;//champion
                    allChamps["teamId"] = ((int)player["teamId"]).ToString();
                    allChamps["botPlayer"] = ((bool)player["leaver"]).ToString();
                    foreach (string col in statKeys)
                    {
                        bool colFound = false;
                        foreach (JObject stat in player["statistics"]["list"]["source"])
                        {
                            if ((string)stat["displayName"] == col)
                            {

                                string val_str = "";
                                switch (stat["value"].Type)
                                {
                                    case JTokenType.Integer:
                                        val_str = ((int)stat["value"]).ToString();
                                        break;
                                    default:
                                        val_str = (string)stat["value"];
                                        break;
                                }
                                al.Add(val_str);
                                colFound = true;
                            }
                        }
                        if (!colFound) al.Add("");
                    }
                    ListViewItem lvi = new ListViewItem((string[])al.ToArray(typeof(string)));
                    lvPlayers.Items.Add(lvi);
                }
            }

        }
    }
}
